<template>
  <div style="padding: 10px;">
    <!-- 搜索功能 -->
    <div class="search-area">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form :inline="true" :model="formSearch" class="demo-form-inline">
            <el-form-item label="学生姓名" prop="name">
              <el-input
                clearable
                v-model="formSearch.name"
                placeholder="请输入学生姓名"
                class="custom-input"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form :inline="true" :model="formSearch" class="demo-form-inline">
            <el-form-item label="学生性别" prop="gender">
              <el-select
                clearable
                v-model="formSearch.gender"
                placeholder="请选择学生性别"
                class="custom-select"
              >
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form :inline="true" :model="formSearch" class="demo-form-inline">
            <el-form-item label="学生年龄" prop="age">
              <el-input
                clearable
                v-model="formSearch.age"
                placeholder="请输入学生年龄"
                class="custom-input"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="toSearch"
            class="search-btn"
          >
            搜索和分页
          </el-button>
          <el-button
            type="primary"
            @click="toAdd"
            icon="el-icon-plus"
            style="margin-left: 10px;"
          >
            录入学生信息
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        :data="studentData"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column
          prop="student_id"
          label="学生学号"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="学生姓名"
          min-width="180"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="gender"
          label="性别"
          align="center"
          width="120"
        >
          <template v-slot="scope">
            <el-tag
              :type="scope.row.gender === '男' ? 'primary' : 'warning'"
              effect="dark"
            >
              {{ scope.row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="age"
          label="年龄"
          align="center"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="class"
          label="班级"
          align="center"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="contact"
          label="联系方式"
          align="center"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="enrollment_date"
          label="入学日期"
          align="center"
          width="150"
        >
          <template v-slot="scope">
            {{ scope.row.enrollment_date.substring(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="300"
          fixed="right"
        >
          <template v-slot="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="toEdit(scope.row)"
              style="color: #409EFF;"
            >
              修改学生信息
            </el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="toDelete(scope.row.id)"
              style="color: #F56C6C; margin-left: 15px;"
            >
              删除学生
            </el-button>
            <el-button
              type="text"
              icon="el-icon-info"
              @click="toDetails(scope.row.id)"
              style="color: #67C23A; margin-left: 15px;"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页功能 -->
    <div class="pagination-area" style="margin-top: 20px;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="params.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="params.pageSize"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
      ></el-pagination>
    </div>

    <!-- 录入与修改的抽屉 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="30%"
      :before-close="handleClose"
    >
      <div style="padding: 20px;">
        <el-form
          ref="studentForm"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="学生学号" prop="student_id">
            <el-input
              v-model="form.student_id"
              placeholder="请输入学生学号"
            ></el-input>
          </el-form-item>
          <el-form-item label="学生姓名" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入学生姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" placeholder="请输入年龄"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="class">
            <el-input v-model="form.class" placeholder="请输入班级"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="contact">
            <el-input v-model="form.contact" placeholder="请输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="入学日期" prop="enrollment_date">
            <el-date-picker
              v-model="form.enrollment_date"
              type="date"
              placeholder="选择入学日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <div style="text-align: right; margin-top: 20px;">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { get, del, post } from '@/utils/request'

export default {
  data() {
    return {
      formSearch: {
        name: '',
        gender: '',
        age: ''
      },
      studentData: [
        {
          id: 1,
          student_id: 'S2023001',
          name: '张伟',
          gender: '男',
          age: '17',
          class: '高一（1）班',
          contact: '138****1234',
          enrollment_date: '2023-09-01'
        },
        {
          id: 2,
          student_id: 'S2023002',
          name: '王芳',
          gender: '女',
          age: '16',
          class: '高一（2）班',
          contact: '139****5678',
          enrollment_date: '2023-09-01'
        },
        {
          id: 3,
          student_id: 'S2023003',
          name: '李强',
          gender: '男',
          age: '18',
          class: '高二（3）班',
          contact: '150****4321',
          enrollment_date: '2022-09-01'
        },
        {
          id: 4,
          student_id: 'S2023004',
          name: '陈静',
          gender: '女',
          age: '17',
          class: '高一（4）班',
          contact: '151****8765',
          enrollment_date: '2023-09-01'
        },
        {
          id: 5,
          student_id: 'S2023005',
          name: '刘洋',
          gender: '男',
          age: '19',
          class: '高三（2）班',
          contact: '152****3456',
          enrollment_date: '2021-09-01'
        },
        {
          id: 6,
          student_id: 'S2023006',
          name: '赵敏',
          gender: '女',
          age: '16',
          class: '高一（5）班',
          contact: '158****7654',
          enrollment_date: '2023-09-01'
        },
        {
          id: 7,
          student_id: 'S2023007',
          name: '孙浩',
          gender: '男',
          age: '18',
          class: '高二（1）班',
          contact: '159****2345',
          enrollment_date: '2022-09-01'
        },
        {
          id: 8,
          student_id: 'S2023008',
          name: '周婷',
          gender: '女',
          age: '17',
          class: '高一（3）班',
          contact: '176****6543',
          enrollment_date: '2023-09-01'
        },
        {
          id: 9,
          student_id: 'S2023009',
          name: '吴刚',
          gender: '男',
          age: '20',
          class: '高三（5）班',
          contact: '177****5432',
          enrollment_date: '2020-09-01'
        },
        {
          id: 10,
          student_id: 'S2023010',
          name: '郑洁',
          gender: '女',
          age: '16',
          class: '高一（6）班',
          contact: '178****4321',
          enrollment_date: '2023-09-01'
        }
      ],
      params: {
        page: 1,
        pageSize: 10
      },
      total: 10,
      drawerVisible: false,
      drawerTitle: '录入学生信息',
      form: {
        student_id: '',
        name: '',
        gender: '',
        age: '',
        class: '',
        contact: '',
        enrollment_date: ''
      },
      rules: {
        student_id: [
          { required: true, message: '请输入学生学号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        class: [
          { required: true, message: '请输入班级', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        enrollment_date: [
          { required: true, message: '请选择入学日期', trigger: 'change' }
        ]
      },
      currentRow: null
    }
  },
  methods: {
    toSearch() {
      this.params.page = 1
      // 在实际应用中，这里应该调用后端接口获取数据
      // 这里仅作为演示，直接使用本地数据
      const filteredData = this.studentData.filter(student => {
        return (
          (this.formSearch.name ? student.name.includes(this.formSearch.name) : true) &&
          (this.formSearch.gender ? student.gender === this.formSearch.gender : true) &&
          (this.formSearch.age ? student.age === this.formSearch.age : true)
        )
      })
      this.studentData = filteredData
      this.total = filteredData.length
    },
    toAdd() {
      this.drawerTitle = '录入学生信息'
      this.currentRow = null
      this.resetForm()
      this.drawerVisible = true
    },
    toEdit(row) {
      this.drawerTitle = '修改学生信息'
      this.currentRow = row
      this.form = {
        student_id: row.student_id,
        name: row.name,
        gender: row.gender,
        age: row.age,
        class: row.class,
        contact: row.contact,
        enrollment_date: row.enrollment_date
      }
      this.drawerVisible = true
    },
    toDelete(id) {
      this.$confirm('此操作将永久删除该学生信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在实际应用中，这里应该调用后端接口删除数据
        // 这里仅作为演示，直接从本地数据中删除
        this.studentData = this.studentData.filter(student => student.id !== id)
        this.total = this.studentData.length
        this.$message({ type: 'success', message: '删除成功' })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    toDetails(id) {
      // 跳转到学生详情页
      this.$router.push({
        path: '/student-detail',
        query: { id: id }
      })
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.params.page = 1
      // 在实际应用中，这里应该调用后端接口获取数据
      // 这里仅作为演示，直接使用本地数据
      this.getPaginatedData()
    },
    handleCurrentChange(val) {
      this.params.page = val
      // 在实际应用中，这里应该调用后端接口获取数据
      // 这里仅作为演示，直接使用本地数据
      this.getPaginatedData()
    },
    getPaginatedData() {
      const start = (this.params.page - 1) * this.params.pageSize
      const end = start + this.params.pageSize
      this.studentData = this.studentData.slice(start, end)
    },
    submitForm() {
      this.$refs.studentForm.validate(valid => {
        if (valid) {
          if (this.currentRow) {
            // 修改学生信息
            const index = this.studentData.findIndex(student => student.id === this.currentRow.id)
            if (index !== -1) {
              this.studentData[index] = {
                ...this.studentData[index],
                ...this.form
              }
              this.$message({ type: 'success', message: '修改成功' })
            }
          } else {
            // 添加新学生
            const newId = this.studentData.length > 0 ? Math.max(...this.studentData.map(student => student.id)) + 1 : 1
            this.studentData.push({
              id: newId,
              ...this.form
            })
            this.total = this.studentData.length
            this.$message({ type: 'success', message: '录入成功' })
          }
          this.drawerVisible = false
        }
      })
    },
    resetForm() {
      this.form = {
        student_id: '',
        name: '',
        gender: '',
        age: '',
        class: '',
        contact: '',
        enrollment_date: ''
      }
      this.$refs.studentForm && this.$refs.studentForm.resetFields()
    },
    handleClose(done) {
      this.resetForm()
      done()
    }
  },
  created() {
    // 在实际应用中，这里应该调用后端接口获取数据
    // 这里直接使用本地数据
    this.getPaginatedData()
  }
}
</script>

<style lang="scss" scoped>
.custom-select {
  width: 100%;
  ::v-deep .el-input__inner {
    border-radius: 4px;
  }
}

.custom-input {
  width: 100%;
  ::v-deep .el-input__inner {
    border-radius: 4px;
  }
}

.search-btn {
  padding: 10px 20px;
  ::v-deep .el-icon-search {
    margin-right: 5px;
  }
}

.el-table {
  ::v-deep th {
    background-color: #f5f7fa !important;
    color: #606266;
    font-weight: 500;
  }
  ::v-deep td {
    padding: 8px 0;
  }
}

.el-pagination {
  ::v-deep .el-pager li {
    min-width: 32px;
    height: 32px;
    line-height: 32px;
    margin: 0 4px;
    border-radius: 4px;
  }
  ::v-deep .btn-next,
  ::v-deep .btn-prev {
    min-width: 32px;
    height: 32px;
    border-radius: 4px;
  }
}
</style>